package cn.itcast.web.shiro;

import cn.itcast.domain.system.Module;
import cn.itcast.domain.system.User;
import cn.itcast.service.cargo.ShippingService;
import cn.itcast.service.system.ModuleService;
import cn.itcast.service.system.UserService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class AuthRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    @Autowired
    private ModuleService moduleService;
    @Reference
    private ShippingService shippingService;

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //1. 获取用户名
        String email  = (String) token.getPrincipal();

        //2. 根据email查询
        User user = userService.findByEmail(email);
        if (user == null) {
            return null;//报错：UnknownAccountException
        }

        //3. 执行到这里说明email正确，同时可以获取到数据库中正确的密码
        String dbPwd = user.getPassword();

        //4. 返回
        // 参数1：传入的身份对象; 通过subject.getPrincipal()拿到的就是这里的参数1
        // 参数2：告诉shiro数据库中正确的密码
        // 参数3：指定为realm的默认名称
        SimpleAuthenticationInfo sai = new SimpleAuthenticationInfo(user,dbPwd,getName());
        return sai;
    }

    // 授权: 告诉shiro登陆用户拥有的权限（根据用户id查询权限）
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //1. 通过方法参数获取用户对象
        User user = (User) principals.getPrimaryPrincipal();

        //2. 根据用户id查询权限
        List<Module> moduleList = moduleService.findModuleByUserId(user.getId());

        //3. 返回
        SimpleAuthorizationInfo sai = new SimpleAuthorizationInfo();
        if (moduleList != null && moduleList.size() > 0) {
            for (Module module : moduleList) {
                // 告诉shiro用户拥有的权限
                sai.addStringPermission(module.getName());
            }
        }
        return sai;
    }
}
